package com.lcxw.hxzbapi.controller.unioncontroller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.entity.pojo.IncomeUnion;
import com.lcxw.hxzbapi.entity.pojo.IncomeUnionDetail;
import com.lcxw.hxzbapi.entity.pojo.Union;
import com.lcxw.hxzbapi.entity.pojo.UnionMember;
import com.lcxw.hxzbapi.entity.pojo.UnionMemberApply;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.requestBean.DealUnionMemberApplyReq;
import com.lcxw.hxzbapi.entity.requestBean.DealUnionMemberIncomeReq;
import com.lcxw.hxzbapi.entity.requestBean.DeleteUnionMemberReq;
import com.lcxw.hxzbapi.entity.requestBean.GetUnionListReq;
import com.lcxw.hxzbapi.entity.requestBean.GetUnionMemIncomeReq;
import com.lcxw.hxzbapi.entity.requestBean.GetUnionMembersReq;
import com.lcxw.hxzbapi.entity.requestBean.JoinUnionReq;
import com.lcxw.hxzbapi.entity.requestBean.RequestParamBasic;
import com.lcxw.hxzbapi.entity.requestBean.SetUnionInfoReq;
import com.lcxw.hxzbapi.entity.requestBean.TurnUnionReq;
import com.lcxw.hxzbapi.entity.requestBean.getJoinListReq;
import com.lcxw.hxzbapi.entity.requestBean.getTurnInListReq;
import com.lcxw.hxzbapi.entity.response.GetJoinListResp;
import com.lcxw.hxzbapi.entity.response.GetUnionListResp;
import com.lcxw.hxzbapi.entity.response.GetUnionMemberResp;
import com.lcxw.hxzbapi.entity.response.IncomeUnionDetailInfo;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.entity.response.ResponseData;
import com.lcxw.hxzbapi.entity.response.TurnInMemberInfo;
import com.lcxw.hxzbapi.service.IncomeUnionDetailService;
import com.lcxw.hxzbapi.service.IncomeUnionService;
import com.lcxw.hxzbapi.service.UnionMemberApplyService;
import com.lcxw.hxzbapi.service.UnionMemberService;
import com.lcxw.hxzbapi.service.UnionService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.AesCBCUtil;
import com.lcxw.hxzbcommon.common.ObsUtil;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
@Slf4j
public class UnionMemberRealization {

    @Resource
    UnionService unionService;

    @Resource
    UnionMemberService unionMemberService;

    @Resource
    MemberRealization memberRealization;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    UnionMemberApplyService unionMemberApplyService;

    @Resource
    IncomeUnionDetailService incomeUnionDetailService;

    @Resource
    IncomeUnionService incomeUnionService;

    private ObsUtil obsUtil = new ObsUtil();

    //申请加入工会的方法
    public Response joinUnionApply(JoinUnionReq joinUnionReq) throws Exception {
        long userId = Long.parseLong(joinUnionReq.getUserId());
        int unionId = joinUnionReq.getUnionId();
        YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
        if (ywpdMember.getRealNameAuth() != 1) {
            return Response.error(ErrorCode.NO_PERMISSION, "未实名认证，不能加入工会");

        }
        UnionMember unionMember = unionMemberService.selectByUserId(userId);
        if (unionMember != null || unionMemberApplyService.isJoinApply(userId)) {
            return Response.error(ErrorCode.ALREADY_EXIST, "已加入工会或已经申请加入工会，无法重复提交");
        } else {
            UnionMemberApply unionMemberApply = new UnionMemberApply();
            unionMemberApply.setUserId(userId);
            unionMemberApply.setUnionId(unionId);
            unionMemberApply.setApply("申请加入");
            unionMemberApply.setStatus("waiting");
            unionMemberApply.setAddTime(StringUtil.getDateTime());
            unionMemberApplyService.insert(unionMemberApply);
            return Response.ok();
        }
    }

    //申请退出工会的方法
    public Response quitUnionApply(JoinUnionReq quitUnionReq) {
        long userId = Long.parseLong(quitUnionReq.getUserId());
        int unionId = quitUnionReq.getUnionId();
        UnionMember unionMember = unionMemberService.selectByUserId(userId);
        if (unionMember == null || unionMember.getUnionId() != unionId) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "您还未加入工会或者不在申请退出的工会中，请刷新后再试");
        }

        UnionMemberApply unionMemberApply = new UnionMemberApply();
        unionMemberApply.setUserId(userId);
        unionMemberApply.setUnionId(unionId);
        unionMemberApply.setApply("申请退出");
        unionMemberApply.setStatus("waiting");
        unionMemberApply.setAddTime(StringUtil.getDateTime());
        unionMemberApplyService.insert(unionMemberApply);
        return Response.ok();
    }

    //工会后台系统登录方法
    public Response login(String telephone, String password) throws Exception {

        //会长登录验证
        Union union = unionService.selectByTelephone(telephone);
        if (union == null) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "您还没有工会，请向官方申请注册工会");
        }
        password = AesCBCUtil.getInstance().encrypt(password);
        String unionPassword = union.getPassword();

        if (!unionPassword.equals(password)) {
            return Response.error(ErrorCode.INVALID_PARAM, "密码错误");
        }

        String token = memberRealization.genToken(telephone);
        JSONObject data = new JSONObject();
        data.put("userId", telephone);
        data.put("token", token);
        data.put("unionId", union.getUnionId());
        data.put("memberType", "manager");

        if (union.getStatus().equals("审核中")) {
            return Response.error(ErrorCode.NEED_INIT, "工会还在审核中，请耐心等待平台审核");
        }

        return Response.ok(data);


    }

    public String uploadUnionPic(MultipartFile file, int unionId) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String imgName = "union/pic/union_" + unionId + "_" + originalFilename;
        return obsUtil.uploadResrouce(imgName, file.getBytes());
    }

    public Response uploadUnionInvoice(MultipartFile file, int id) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String imgName = "union/invoice/收入单号_" + id + "_" + originalFilename;
        String url = obsUtil.uploadResrouce(imgName, file.getBytes());
        IncomeUnion incomeUnion = incomeUnionService.selectById(id);
        incomeUnion.setInvoice(url);
        incomeUnion.setStatus("3");
        incomeUnionService.updateById(incomeUnion);
        return Response.ok();
    }

    public Response setUnionInfo(SetUnionInfoReq setUnionInfoReq) {

        int unionId = setUnionInfoReq.getUnionId();
        String telephone = setUnionInfoReq.getUserId();
        String unionName = setUnionInfoReq.getUnionName();
        String password = setUnionInfoReq.getPassword();
        try {
            password = AesCBCUtil.getInstance().encrypt(password);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("公会密码初始化加密失败！");
            return Response.error(ErrorCode.INTERNAL_ERROR, "服务器内部错误");
        }
        String img = setUnionInfoReq.getImg();
        String info = setUnionInfoReq.getInfo();
        String invite = setUnionInfoReq.getInvite();
        Union union = unionService.selectById(unionId);
        if (!union.getTelephone().equals(telephone)) {
            return Response.error(ErrorCode.NO_PERMISSION, "您不是工会会长，无权限设置工会信息");
        }
        union.setImg(img);
        union.setUnionName(unionName);
        union.setPassword(password);
        union.setInfo(info);
        union.setInvite(invite);
        union.setStatus("正常");
        unionService.update(union);
        return Response.ok();
    }

    //获取工会列表的方法
    public Response getUnionList(GetUnionListReq requestBody) {
        long userId = Long.parseLong(requestBody.getUserId());
        String unionName = requestBody.getUnionName();
        UnionMember unionMember = unionMemberService.selectByUserId(userId);

        List<Union> unionList = unionService.getAll(unionName);

        List<GetUnionListResp> data = new ArrayList<>();
        for (Union union : unionList
        ) {
            if (!union.getStatus().equals("正常")) {
                continue;
            }
            GetUnionListResp getUnionListResp = new GetUnionListResp();
            BeanUtils.copyProperties(union, getUnionListResp);
            if (unionMember != null && unionMember.getUnionId() == union.getUnionId()) {
                getUnionListResp.setIsJoin(1);
            } else if (unionMemberApplyService
                .isJoinOrQuitApply(userId, union.getUnionId(), "申请加入")) {
                getUnionListResp.setIsJoin(2);
            } else if (unionMemberApplyService
                .isJoinOrQuitApply(userId, union.getUnionId(), "申请退出")) {
                getUnionListResp.setIsJoin(3);
            } else if (unionMember == null) {
                getUnionListResp.setIsJoin(0);
            }

            data.add(getUnionListResp);
        }
        return Response.ok(data);
    }

    //获取我的工会信息
    public Response getMyUnionInfo(RequestParamBasic requestBody) {

        long userId = Long.parseLong(requestBody.getUserId());
        UnionMember unionMember = unionMemberService.selectByUserId(userId);
        if (unionMember == null) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "您还没有加入工会");
        }
        int unionId = unionMember.getUnionId();
        Union union = unionService.selectById(unionId);
        GetUnionListResp getUnionListResp = new GetUnionListResp();
        BeanUtils.copyProperties(union, getUnionListResp);

        getUnionListResp.setIsJoin(1);
        if (unionMemberApplyService.isJoinOrQuitApply(userId, unionId, "申请加入")) {
            getUnionListResp.setIsJoin(2);
        } else if (unionMemberApplyService.isJoinOrQuitApply(userId, unionId, "申请退出")) {
            getUnionListResp.setIsJoin(3);
        }
        return Response.ok(getUnionListResp);

    }

    //获取工会成员方法
    public Response getUnionMembers(GetUnionMembersReq getUnionMembersReq) throws Exception {
        int unionId = getUnionMembersReq.getUnionId();
        String telephone = getUnionMembersReq.getTelephone();
        int pageNum = getUnionMembersReq.getPageNum();
        int pageSize = getUnionMembersReq.getPageSize();

        Long queryUserId = null;

        if (!StringUtil.isEmpty(telephone)) {
            queryUserId = ywpdMemberService.selectYwpdMemberByTelephone(telephone).getUserId();
        }

        IPage<UnionMember> unionMembers = unionMemberService
            .getUnionMembers(unionId, queryUserId, pageNum, pageSize);

        List<GetUnionMemberResp> unionMemberList = new ArrayList<>();
        for (UnionMember unionMember : unionMembers.getRecords()
        ) {
            GetUnionMemberResp getUnionMemberResp = new GetUnionMemberResp();
            BeanUtils.copyProperties(unionMember, getUnionMemberResp);
            Long userId = unionMember.getUserId();
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
            getUnionMemberResp.setJoinType("自主申请");
            getUnionMemberResp.setImgUrl(ywpdMember.getImgUrl());
            getUnionMemberResp.setNickName(ywpdMember.getNickName());
            getUnionMemberResp.setTelephone(ywpdMember.getTelephone());
            unionMemberList.add(getUnionMemberResp);
        }

        JSONObject data = new JSONObject();
        data.put("total", unionMembers.getTotal());
        data.put("unionMemberList", unionMemberList);
        return Response.ok(data);

    }

    //处理工会申请
    public Response dealUnionMemberApply(DealUnionMemberApplyReq dealUnionMemberApplyReq)
        throws Exception {

        int id = dealUnionMemberApplyReq.getId();
        UnionMemberApply unionMemberApply = unionMemberApplyService.selectById(id);
        String telephone = dealUnionMemberApplyReq.getUserId();
        Union union = unionService.selectByTelephone(telephone);
        if (union == null || union.getUnionId() != unionMemberApply.getUnionId()) {
            return Response.error(ErrorCode.NO_PERMISSION, "您不是公会会长，没有权限处理该请求");
        }
        String apply = unionMemberApply.getApply();
        String decision = dealUnionMemberApplyReq.getDecision();
        unionMemberApply.setDealTime(StringUtil.getDateTime());
        unionMemberApply.setStatus(decision);
        if (apply.equals("申请加入")) {
            if (decision.equals("agree")) {
                UnionMember unionMember = new UnionMember();
                unionMember.setUserId(unionMemberApply.getUserId());
                unionMember.setUnionId(unionMemberApply.getUnionId());
                unionMember.setAddTime(StringUtil.getDateTime());
                unionMemberService.insert(unionMember);
                YwpdMember ywpdMember = ywpdMemberService
                    .selectYwpdMemberByUserId(unionMemberApply.getUserId());
                ywpdMember.setSign(1);
                ywpdMemberService.updateYwpdMember(ywpdMember);
            }

        } else if (apply.equals("申请退出")) {
            if (decision.equals("agree")) {
                unionMemberService.deleteByUserId(unionMemberApply.getUserId());
                YwpdMember ywpdMember = ywpdMemberService
                    .selectYwpdMemberByUserId(unionMemberApply.getUserId());
                ywpdMember.setSign(0);
                ywpdMemberService.updateYwpdMember(ywpdMember);
            }
        }

        unionMemberApplyService.update(unionMemberApply);

        return Response.ok();
    }

    //踢出公会成员
    public Response deleteMember(DeleteUnionMemberReq deleteUnionMemberReq) {
        int id = deleteUnionMemberReq.getId();
        String telephone = deleteUnionMemberReq.getUserId();
        Union union = unionService.selectByTelephone(telephone);
        UnionMember unionMember = unionMemberService.selectById(id);
        if (union == null || union.getUnionId() != unionMember.getUnionId()) {
            return Response.error(ErrorCode.NO_PERMISSION, "您不是该公会会长，没有权限处理该请求");
        }

        unionMemberService.deleteById(id);

        UnionMemberApply unionMemberApply = new UnionMemberApply();
        unionMemberApply.setUserId(unionMember.getUserId());
        unionMemberApply.setUnionId(unionMember.getUnionId());
        unionMemberApply.setApply("踢出公会");
        unionMemberApply.setAddTime(StringUtil.getDateTime());

        unionMemberApplyService.insert(unionMemberApply);

        return Response.ok();

    }

    //获取正在申请入会或者申请退出公会的列表
    public Response getJoinList(getJoinListReq getJoinListReq) throws Exception {

        int unionId = getJoinListReq.getUnionId();
        int pageNum = getJoinListReq.getPageNum();
        int pageSize = getJoinListReq.getPageSize();
        String apply = getJoinListReq.getApply();
        Long queryUserId = null;
        String telephone = getJoinListReq.getTelephone();
        if (!StringUtil.isEmpty(telephone)) {
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByTelephone(telephone);
            if (ywpdMember == null) {
                return Response.error(ErrorCode.DATA_NOT_EXIST, "没有查到数据");
            }
            queryUserId = ywpdMember.getUserId();
        }

        IPage<UnionMemberApply> page = unionMemberApplyService
            .getJoinListByUnionId(unionId, queryUserId, apply, pageNum, pageSize);
        long total = page.getTotal();

        List<UnionMemberApply> unionMemberApplyList = page.getRecords();

        List<GetJoinListResp> joinListRespList = new ArrayList<>();

        for (UnionMemberApply unionMemberApply : unionMemberApplyList
        ) {
            GetJoinListResp getJoinListResp = new GetJoinListResp();
            BeanUtils.copyProperties(unionMemberApply, getJoinListResp);
            Long userId = unionMemberApply.getUserId();
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
            getJoinListResp.setTelephone(ywpdMember.getTelephone());
            getJoinListResp.setImgUrl(ywpdMember.getImgUrl());
            getJoinListResp.setNickName(ywpdMember.getNickName());
            getJoinListResp.setSex(ywpdMember.getSex());
            getJoinListResp.setJoinType("自主加入");
            joinListRespList.add(getJoinListResp);
        }

        ResponseData data = new ResponseData();
        data.setTotal(total);
        data.setList(joinListRespList);
        return Response.ok(data);

    }

    //申请转会
    public Response turnUnionReq(TurnUnionReq turnUnionReq) {
        long userId = Long.parseLong(turnUnionReq.getUserId());
        int fromUnionId = turnUnionReq.getFromUnionId();
        int toUnionId = turnUnionReq.getToUnionId();
        if (unionMemberService.selectByUserId(userId) == null
            || unionMemberService.selectByUserId(userId).getUnionId() != fromUnionId) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "您不在当前公会，不能申请转会");
        }
        UnionMemberApply unionMemberApply = new UnionMemberApply();
        unionMemberApply.setUserId(userId);
        unionMemberApply.setApply("申请转会");
        unionMemberApply.setStatus("waiting");
        unionMemberApply.setAddTime(StringUtil.getDateTime());
        unionMemberApply.setTurnOutUnionId(fromUnionId);
        unionMemberApply.setTurnOutStatus("waiting");
        unionMemberApply.setTurnInUnionId(toUnionId);
        unionMemberApply.setTurnInStatus("waiting");
        unionMemberApplyService.insert(unionMemberApply);
        return Response.ok();
    }

    public Response getTurnInList(getTurnInListReq getTurnInListReq) {
        int unionId = getTurnInListReq.getUnionId();
        int pageNum = getTurnInListReq.getPageNum();
        int pageSize = getTurnInListReq.getPageSize();
        IPage<UnionMemberApply> page = unionMemberApplyService
            .getTurnInByUnionId(unionId, pageNum, pageSize);
        ResponseData data = new ResponseData();
        data.setTotal(page.getTotal());
        List<UnionMemberApply> records = page.getRecords();

        List<TurnInMemberInfo> list = new ArrayList<>();
        for (UnionMemberApply unionMemberApply : records
        ) {
            Integer turnOutUnionId = unionMemberApply.getTurnOutUnionId();
            Union union = unionService.selectById(turnOutUnionId);
            Long userId = unionMemberApply.getUserId();
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);

            TurnInMemberInfo turnInMemberInfo = new TurnInMemberInfo();
            BeanUtils.copyProperties(unionMemberApply, turnInMemberInfo);
            turnInMemberInfo.setImgUrl(ywpdMember.getImgUrl());
            turnInMemberInfo.setNickName(ywpdMember.getNickName());
            turnInMemberInfo.setSex(ywpdMember.getSex());
            turnInMemberInfo.setTurnOutUnionName(union.getUnionName());
            list.add(turnInMemberInfo);
        }

        data.setList(list);
        return Response.ok(data);
    }


    public Response getUnionMemberIncomeList(GetUnionMemIncomeReq getUnionMemIncomeReq)
        throws Exception {
        String telephone = getUnionMemIncomeReq.getUserId();
        String status = getUnionMemIncomeReq.getStatus();
        String term = getUnionMemIncomeReq.getTerm();
        int unionId = getUnionMemIncomeReq.getUnionId();
        int pageNum = getUnionMemIncomeReq.getPageNum();
        int pageSize = getUnionMemIncomeReq.getPageSize();
        String queriedTelephone = getUnionMemIncomeReq.getTelephone();

        Union union = unionService.selectById(unionId);
        if (union == null || !union.getTelephone().equals(telephone)) {
            return Response.error(ErrorCode.NO_PERMISSION, "您不是会长，无权限操作");
        }
        Long userId = null;
        if (!StringUtil.isEmpty(queriedTelephone)) {
            userId = ywpdMemberService.selectYwpdMemberByTelephone(queriedTelephone).getUserId();
        }

        IPage<IncomeUnionDetail> page = incomeUnionDetailService
            .selectList(unionId, term, userId, status, pageNum, pageSize);

        int total = (int) page.getTotal();
        List<IncomeUnionDetail> records = page.getRecords();
        List<IncomeUnionDetailInfo> list = new ArrayList<>();
        for (IncomeUnionDetail incomeUnionDetail : records
        ) {
            IncomeUnionDetailInfo incomeUnionDetailInfo = new IncomeUnionDetailInfo();
            BeanUtils.copyProperties(incomeUnionDetail, incomeUnionDetailInfo);
            YwpdMember ywpdMember = ywpdMemberService
                .selectYwpdMemberByUserId(incomeUnionDetail.getUserId());

            incomeUnionDetailInfo.setNickName(ywpdMember.getNickName());
            incomeUnionDetailInfo.setRealName(ywpdMember.getRealName());
            incomeUnionDetailInfo.setTelephone(ywpdMember.getTelephone());
            incomeUnionDetailInfo.setImgUrl(ywpdMember.getImgUrl());

            list.add(incomeUnionDetailInfo);

        }
        ResponseData data = new ResponseData();
        data.setTotal(total);
        data.setList(list);
        return Response.ok(data);

    }

    public Response dealUnionMemberIncome(DealUnionMemberIncomeReq dealUnionMemberIncomeReq) {

        int id = dealUnionMemberIncomeReq.getId();
        String decision = dealUnionMemberIncomeReq.getDecision();
        String orderNum = dealUnionMemberIncomeReq.getOrderNum();
        String reason = dealUnionMemberIncomeReq.getReason();
        String transferType = dealUnionMemberIncomeReq.getTransferType();

        if (decision.equals("agree")) {

            if (StringUtil.isEmpty(orderNum) || StringUtil.isEmpty(transferType)) {
                return Response.error(ErrorCode.INVALID_PARAM, "同意打款需要携带转账类型和打款单号");
            }

            IncomeUnionDetail incomeUnionDetail = incomeUnionDetailService.selectById(id);
            incomeUnionDetail.setStatus("1");
            incomeUnionDetail.setTransferType(transferType);
            incomeUnionDetail.setOrderNum(orderNum);
            incomeUnionDetailService.updateById(incomeUnionDetail);

        }

        if (decision.equals("refuse")) {

            if (StringUtil.isEmpty(reason)) {

                return Response.error(ErrorCode.INVALID_PARAM, "拒绝打款需要携带原因");
            }

            IncomeUnionDetail incomeUnionDetail = incomeUnionDetailService.selectById(id);
            incomeUnionDetail.setStatus("2");
            incomeUnionDetail.setReason(reason);
            incomeUnionDetailService.updateById(incomeUnionDetail);
        }

        return Response.ok();

    }
}
